package com.yn.iotxiao.controller.Event;

import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.Hik.HttpAysncClientUtil;
import com.yn.iotxiao.Utils.HttpHelper;
import com.yn.iotxiao.Utils.JsonHelper;
import com.yn.iotxiao.model.Hik.HikEvent;
import com.yn.iotxiao.sql.entity.Device.DeviceInfo;
import com.yn.iotxiao.sql.entity.Record.PassRecord;
import com.yn.iotxiao.sql.services.Developer.DeveloperInfoService;
import com.yn.iotxiao.sql.services.Device.DeviceInfoService;
import com.yn.iotxiao.sql.services.Record.PassRecordService;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

@RequestMapping("/event")
@Slf4j
@RestController
public class EventController {

    @Autowired
    PassRecordService service;
    @Autowired
    DeveloperInfoService dService;
    @Autowired
    DeviceInfoService deviceInfoService;

    private String Url;
    @GetMapping("alertStream")
    public String startAlertSteam() throws Exception{

        List<DeviceInfo> devices = deviceInfoService.getWithType(2);
        if (devices.size() == 0) {
            throw new Exception("没有需要订阅的设备");
        }

        DeviceInfo device = devices.get(0);
        HttpAysncClientUtil.iPort = 80;
        HttpAysncClientUtil.strIP = device.getIp();
        log.info("订阅设备事件："+device.getName());
        Url = String.format("http://%s/ISAPI/Event/notification/alertStream",device.getIp());

        HttpAysncClientUtil.HttpAysncInit(device.getLoginId(),device.getPassword());

        Thread thread =new Thread(llink);
        thread.start();



        return "订阅成功";
//        return  deviceInfoService.startEventSubscribe();
    }
    private LongLinkThread llink=new LongLinkThread();
    public class LongLinkThread implements Runnable{
        @Override
        public void run() {
            // TODO Auto-generated method stub
            HttpAysncClientUtil.LonLink(Url, "all", false);

//            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "xb0100xb"));
//
//
//            CloseableHttpClient httpClient = HttpClients.custom()
//                    .setDefaultCredentialsProvider(credentialsProvider)
//                    .build();
//
//            HttpGet httpGet = new HttpGet(Url);
//            httpGet.addHeader("Connection", "keep-alive");
            log.info("Url："+ Url);
//            CloseableHttpResponse response = null;
//            try {
//                response = httpClient.execute(httpGet);
//                HttpEntity entity = response.getEntity();
//
//                String responseBody = EntityUtils.toString(entity);
//                log.info("接受数据：" + responseBody);
//            } catch (IOException e) {
//                log.info("接受数据异常：" + e.getLocalizedMessage());
//                throw new RuntimeException(e);
//            }

        }
    }

    @PostMapping
    public String event(HttpServletRequest request) {

        Enumeration<String> paraNames = request.getParameterNames();
        List<PassRecord> list = new ArrayList<>();
        var devices = deviceInfoService.getList("",1,50);
        for (Enumeration e = paraNames; e.hasMoreElements(); ) {

            PassRecord record = new PassRecord();
            String thisName = e.nextElement().toString();
            String thisValue = request.getParameter(thisName);
            log.info("参数：" + thisName + "--------------" + thisValue);
            if (!StringUtils.isBlank(thisValue)) {
                HikEvent event = JsonHelper.json2Obj(thisValue, HikEvent.class);

                if (event.getAccessControllerEvent().getMajorEventType() == 5
                && event.getAccessControllerEvent().getSubEventType() == 75
              ) {
                    //  && event.getAccessControllerEvent().getPicturesNumber() > 0
                    record.setIp(event.getIpAddress());
                    record.setDeviceserial(devices.stream().filter(a -> a.getIp().equals(event.getIpAddress())).findFirst().get().getSerialnumber());
                    record.setMacaddress(event.getMacAddress());
                    record.setDatetime(event.getDateTime());
                    record.setName(event.getAccessControllerEvent().getName());
                    record.setEmployeeno(event.getAccessControllerEvent().getEmployeeNoString());
                    record.setEventtype("open_event_access");
                    //人脸认证事件
                    try {
                        for (Part part : request.getParts()) {
                            log.info("文件名称："+ part.getName());
                            log.info("文件大小："+ part.getSize());
                            log.info("contentType："+ part.getContentType());

                            if (!StringUtils.isBlank(part.getContentType())  && part.getContentType().equals("image/jpeg")) {
                                InputStream stream = part.getInputStream();
                                String fileName = String.format("%s%s", UUID.randomUUID().toString(),".jpg");
                                LocalDateTime dateTime = LocalDateTime.now();
                                DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                                String formattedDateTime2 = dateTime.format(formatter2);
                                String SavePath = Paths.get("/event/record/" + formattedDateTime2).toString();
                                var absolutePath = Paths.get(System.getProperty("user.dir") + "/static") + SavePath;

                                File file =new File(absolutePath);
                                log.info("路径：" + absolutePath);
                                if (!file.exists()) {
                                    file.mkdirs();
                                }
                                Path path = Paths.get(SavePath).resolve(fileName);
                                File destinationFile = new File(Paths.get(System.getProperty("user.dir") + "/static").toString() + path);
                                FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

// 复制文件内容
                                byte[] buffer = new byte[1024];
                                int bytesRead;
                                while ((bytesRead = stream.read(buffer)) != -1) {
                                    fileOutputStream.write(buffer, 0, bytesRead);
                                }
                                stream.close();
                                fileOutputStream.close();

                                var scheme = request.getHeader("X-Forwarded-Scheme");
                                if (StringUtils.isBlank(scheme))
                                {
                                    scheme = request.getScheme();
                                }
                                String requestUrl =String.format("%s://%s", scheme, request.getHeader("Host"));
                                String vPath = System.getenv("VIRTUAL_PATH");
                                if (!StringUtils.isBlank(vPath))
                                {
                                    requestUrl += vPath;
                                }
                                var url =  String.format("%s/static%s",requestUrl,path);
                                event.getAccessControllerEvent().setPhoto(url);
                                record.setPictureurl(url);

                                log.info("图片地址："+ url);
                            }

                        }
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    } catch (ServletException ex) {
                        throw new RuntimeException(ex);
                    }
                    list.add(record);
                }
            }


        }

//        log.info("写入记录：" + list.size());
        if (list.size() > 0) {
            service.batchInsert(list);
            //判断是否推送
            var developers = dService.getPushList();
            if (developers.size() > 0) {
                for (var developer: developers
                     ) {
                    log.info("推送数据：" + developer.getTitle());
                    var url = developer.getPushurl();

                    HttpHelper.doPostEvent(list,url);
                }
            }
        }


//        String contentType = request.getContentType();
//
//        log.info("接受数据：" + contentType);
//        if (contentType.contains("application/json")) {
//            // json 解析...
//           log.info("json数据");
//           log.info("数据：" + RequestUtils.readReqStr(request));
//        } else if (contentType.contains("multipart/form-data")) {
//            // form 表单解析 ...
//            log.info("xml");
//            log.info("xml数据："+ RequestUtils.readReqStr(request));
//            try {
//                for (Part part : request.getParts()) {
//                    log.info("文件名称："+ part.getName());
//                    log.info("文件大小："+ part.getSize());
//                    log.info("contentType："+ part.getContentType());
//                    InputStream stream = part.getInputStream();
//                }
//
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            } catch (ServletException e) {
//                throw new RuntimeException(e);
//            }
////            log.info("数据：" + RequestUtils.readReqXml(request));
//        }

        return "ok";
    }
}
